package cn.tedu.account.tcc;

import cn.tedu.account.entity.Account;
import cn.tedu.account.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class AccountTCCActionImpl implements AccountTCCAction {

    @Autowired
    private AccountMapper accountMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long userId, BigDecimal money) {
        Account account = accountMapper.selectById(userId);
        //a.compareTo(b) a大返回正数,a小返回负数,相同返回0
        if (account.getResidue().compareTo(money) < 0){
            throw new RuntimeException("金额不足");
        }
        accountMapper.updateFrozen(userId, money);

//        if (Math.random()<0.8){
//            throw new RuntimeException("模拟失败");
//        }
        ResultHolder.setResult(AccountTCCAction.class, ctx.getXid(), "p");
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        if (ResultHolder.getResult(AccountTCCAction.class,ctx.getXid())==null){
            return true;
        }
        Long userId = Long.valueOf(ctx.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());
        accountMapper.updateFrozenToUsed(userId,money);
        ResultHolder.removeResult(AccountTCCAction.class, ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(AccountTCCAction.class,ctx.getXid())==null){
            return true;
        }
        Long userId = Long.valueOf(ctx.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());
        accountMapper.updateFrozenToResidue(userId,money);
        ResultHolder.removeResult(AccountTCCAction.class, ctx.getXid());
        return true;
    }
}
